<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="业务场景编号" prop="categoryId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.categoryId"-->
      <!--          placeholder="请输入业务场景编号"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="业务场景" prop="id">
        <treeselect v-model="queryParams.categoryId" style="width: 350px" :options="categoryOptions"
                    :normalizer="normalizer" :show-count="true" placeholder="请选择父类机构"
        />
      </el-form-item>
      <el-form-item label="试题id" prop="questionId">
        <el-input
          v-model="queryParams.questionId"
          placeholder="请输入试题id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试题类型" prop="questionType">
        <el-select v-model="queryParams.questionType" clearable style="width: 100%;"
                   placeholder="请选择试题类型：1 问答题， 2 单选，3 多选，4 判断，5 评分"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="questionName">
        <el-input
          v-model="queryParams.questionName"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="唯一标识" prop="unCode">
        <el-input
          v-model="queryParams.unCode"
          placeholder="请输入唯一标识"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序号" prop="sortNo">
        <el-input
          v-model="queryParams.sortNo"
          placeholder="请输入排序号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="题目价值" prop="questionValue">
        <el-input
          v-model="queryParams.questionValue"
          placeholder="请输入题目价值"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:items:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:items:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:items:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:items:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" show-overflow-tooltip stripe :data="itemsList"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="id"/>
      <el-table-column label="业务场景编号" align="center" prop="categoryId"/>
      <el-table-column label="所属问卷" align="center" show-overflow-tooltip prop="title"/>
      <el-table-column label="试题id" align="center" prop="questionId"/>
      <el-table-column label="试题类型" align="center" prop="questionType"/>
      <el-table-column label="标题" align="center" prop="questionName"/>
      <el-table-column label="唯一标识" align="center" prop="unCode"/>
      <el-table-column label="排序号" align="center" prop="sortNo"/>
      <el-table-column label="题目价值" align="center" prop="questionValue"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:items:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:items:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试题题目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="所属问卷" prop="id" style="width:100% ;" align="center">
            <treeselect v-model="form.categoryId" :options="categoryOptions" :normalizer="normalizer"
                        :show-count="true" placeholder="请选择父类机构"
            />
          </el-form-item>
          <!--        <el-form-item label="试题id" prop="questionId">-->
          <!--          <el-input v-model="form.questionId" placeholder="请输入试题id" />-->
          <!--        </el-form-item>-->
          <el-form-item label="试题类型" prop="questionType" style="width:450px;display: inline-block" align="center">
            <el-select v-model="form.questionType" clearable style="width: 100%;"
                       placeholder="请选择试题类型：1 问答题， 2 单选，3 多选，4 判断，5 评分"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题" prop="questionName" style="width: 450px;display: inline-block" align="center">
            <el-input v-model="form.questionName" placeholder="请输入标题"/>
          </el-form-item>
          <!--        <el-form-item label="唯一标识" prop="unCode">-->
          <!--          <el-input v-model="form.unCode" placeholder="请输入唯一标识" />-->
          <!--        </el-form-item>-->
          <el-form-item label="排序号" prop="sortNo" style="width: 450px;display: inline-block" align="center">
            <el-input v-model="form.sortNo" placeholder="请输入排序号"/>
          </el-form-item>
          <el-form-item label="题目价值" prop="questionValue" style="width: 450px;display: inline-block" align="center">
            <el-input v-model="form.questionValue" placeholder="请输入题目价值"/>
          </el-form-item>
          <el-form-item label="试题选项" prop="questionAnswerList" style="width: 100%" align="center"
                        v-if="form.questionType == 2 || form.questionType == 3"
          >
            <template slot-scope="scope">
            <el-table
              :data="questionAnswerList"
              :header-cell-style="{background:'rgba(104,54,174,0.53)', color:'white', 'line-hight':'30px', 'text-align': 'center'}"
              style="width: 100%">
              <el-table-column
                align="center"
                type="index"
                width="50">
                <template slot="header" slot-scope="scope">
                  <el-button type="success" size="medium" icon="el-icon-circle-plus" circle @click="addQuestionAnswer"></el-button>
                </template>
                <template slot-scope="scope">
                  <span> {{scope.row.id == null ? scope.$index + 1 : scope.row.id}} </span>
                </template>
              </el-table-column>
              <el-table-column
                label="选项"
                align="center"
                >
                <template slot-scope="scope">
<!--                  <el-input v-model="scope.row.questionSelect" placeholder="请输入选项"/>-->
                  <el-select v-model="scope.row.questionSelect" placeholder="请选择">
                    <el-option
                      v-for="item in option1"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="选项内容"
                align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.questionAnswer" placeholder="请输入选项"/>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="操作"
                width="120">
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="deleteRow(scope.row, questionAnswerList)"
                    type="text"
                    size="small">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            </template>
          </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItems, getItems, delItems, addItems, updateItems, exportItems } from '@/api/question/items'
import { delAnswer} from '@/api/question/answer'

import { treeselect } from '@/api/question/scenario'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Items',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 问卷调查树选项
      categoryOptions: undefined,
      // 总条数
      total: 0,
      // 试题题目管理表格数据
      itemsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        questionId: null,
        questionType: null,
        questionName: null,
        unCode: null,
        sortNo: null,
        questionValue: null
      },
      option1: [{
        value: 'A',
        label: 'A'
      }, {
        value: 'B',
        label: 'B'
      }, {
        value: 'C',
        label: 'C'
      }, {
        value: 'D',
        label: 'D'
      }, {
        value: 'E',
        label: 'E'
      }],
      options: [{
        value: '1',
        label: '问答题'
      }, {
        value: '2',
        label: '单选题'
      }, {
        value: '3',
        label: '多选题'
      }, {
        value: '4',
        label: '判断题'
      }, {
        value: '5',
        label: '评分（打星）'
      }],
      questionAnswerList: [{
        questionSelect: '',
        questionAnswer: ''
      }],
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        questionType: [
          { required: true, message: '请选择试题类型', trigger: 'blur' }
        ],
        questionName: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        sortNo: [
          { required: true, message: '请输入排序号', trigger: 'blur' }
        ],
        questionValue: [
          { required: true, message: '请输入题目价值', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
  },
  methods: {

    deleteRow(index, rows) {
      // rows.splice(index, 1);
      this.questionAnswerList = this.questionAnswerList.filter(item => item.id !== index.id)
    },
    addQuestionAnswer(){
      this.questionAnswerList.push({
        questionSelect: '',
        questionAnswer: ''
      })
    },
    /** 查询试题题目管理列表 */
    getList() {
      this.loading = true
      listItems(this.queryParams).then(response => {
        this.itemsList = response.rows
        for (let i = 0; i < this.itemsList.length; i++) {
          if (this.itemsList[i].questionType == 1) {
            this.itemsList[i].questionType = '问答题'
          } else if (this.itemsList[i].questionType == 2) {
            this.itemsList[i].questionType = '单选题'
          } else if (this.itemsList[i].questionType == 3) {
            this.itemsList[i].questionType = '多选题'
          } else if (this.itemsList[i].questionType == 4) {
            this.itemsList[i].questionType = '判断题'
          } else if (this.itemsList[i].questionType == 5) {
            this.itemsList[i].questionType = '评分（打星）'
          }
        }
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        questionId: null,
        questionType: null,
        questionName: null,
        unCode: null,
        sortNo: null,
        questionValue: null,
        createTime: null,
        updateTime: null
      }
      this.questionAnswerList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.queryParams.categoryId === 1) {
        this.queryParams.categoryId = null
      }
      this.queryParams.pageNum = 1
      // console.log(this.queryParams)
      this.getList()
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.title,
        children: node.childList
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 查询业务场景下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.categoryOptions = response.data
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getTreeselect()
      this.open = true
      this.title = '添加试题题目管理'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      this.getTreeselect()
      getItems(id).then(response => {
        this.form = response.data
        this.questionAnswerList = response.data.questionAnswerList
        if(response.data.questionAnswerList === undefined)  this.questionAnswerList = []
        this.open = true
        this.title = '修改试题题目管理'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.questionAnswerList = this.questionAnswerList
            updateItems(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            // 将questionAnswerList设置为form的一个属性
            this.form.questionAnswerList = this.questionAnswerList
            addItems(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    delAnswerOne(row,questionId) {

      const ids = row.id || this.ids
      this.$confirm('是否确认删除试题答案编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delAnswer(ids)
      }).then(() => {
        // this.getList()
        // 重新 查询该问题 详情信息
        this.reset()
        this.getTreeselect()
        getItems(questionId).then(response => {
          this.form = response.data
          console.log(this.form)
          this.questionAnswerList = response.data.questionAnswerList
          this.open = true
          this.title = '修改试题题目管理'
        })
        this.msgSuccess('删除成功')
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除试题题目管理编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delItems(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有试题题目管理数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportItems(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>


